<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏房间</title>
    <link rel="stylesheet" href="./css/common.css">
    <link rel="stylesheet" href="./css/game_room.css">
    <style>
        html, body {
            height: 100%;
            background-image: url(./img/bk_img_game_room.jpg);
            background-repeat: no-repeat;
            background-position: center;
            background-size: cover;
        }
    </style>
  
</head>
<body>
    <div class="nav" id="room_id_flag"></div>
    <div class="container">
        <div id="chess_area">
            <!-- 棋盘区域, 需要基于 canvas 进行实现 -->
            <canvas id="chess" width="450px" height="450px" style="margin-top: 20px;"></canvas>
            <!-- 显示区域 -->
            <div id="screen">连接中... </div>
        </div>
        <div id="chat_area" width="400px" height="300px">
            <div id="chat_show">
                <p id="self_msg">您可以直接和对手聊天</p></br>
                <p id="peer_msg">但是不要说脏话呀</p></br>
            </div>
            <div id="msg_show">
                <input type="text" id="chat_input">
                <img src="./img/send.png" alt="加载失败" id="chat_button">
            </div>
        </div>

       
        <button id="return_hall">返回大厅</button>
        <button id="save_data">保存数据</button>
        <p id = "count_down"></p>
        <p id = "user_tip"></p>

    </div>
    <script>
        let chessBoard = [];
        let BOARD_ROW_AND_COL = 15;
        let chess = document.getElementById('chess');
        let context = chess.getContext('2d');//获取chess控件的2d画布
        var global_winner = 0;
        var set_time_out_id = 0;
        var next_time = 0;
        var if_auto_select = false;

        var room_info = null;//用于保存房间信息 
        var is_me = false; //是否轮到自己走

        var hidden_sd_bt = document.getElementById("save_data");
        hidden_sd_bt.hidden = true;

        function initGame() {
            initBoard();
            context.strokeStyle = "#000000";
            drawChessBoard();
        }
        
        function initBoard() {
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                chessBoard[i] = [];
                for (let j = 0; j < BOARD_ROW_AND_COL; j++) {
                    chessBoard[i][j] = 0;
                }
            }
        }
        // 绘制棋盘网格线
        function drawChessBoard() {
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                context.moveTo(15 + i * 30, 15);
                context.lineTo(15 + i * 30, 430); //横向的线条
                context.stroke();
                context.moveTo(15, 15 + i * 30);
                context.lineTo(435, 15 + i * 30); //纵向的线条
                context.stroke();
            }
        }

        //给棋手绘制棋子
        function oneStep(i, j, isWhite) {
            if (i < 0 || j < 0) return;
            context.beginPath();
            context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
            context.closePath();
            var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
            // 区分黑白子
            if (!isWhite) {
                gradient.addColorStop(0, "#D1D1D1");
                gradient.addColorStop(1, "#FCFCFC");
            } else {
                gradient.addColorStop(0, "#0A0A0A");
                gradient.addColorStop(1, "#636766");
            }
            context.fillStyle = gradient;
            context.fill();
        }

        //绘制所有已经下过的棋子
        function oneStep_viewer(board_msg)
        {
            for (var i = 0; i < 225; i++)
            {   
                var row = Math.floor(i/15);
                var col = i - row * 15;
                if (board_msg[i] == '1')
                {                
                    oneStep(col, row, true)
                }
                else if (board_msg[i] == '2')
                {
                    oneStep(col, row, false);
                }
            }
        }

        //棋盘区域的点击事件
        chess.onclick = function (e) {
            //  1. 获取下棋位置，判断当前下棋操作是否正常
            //      1. 当前是否轮到自己走棋了
            //      2. 当前位置是否已经被占用
            //  2. 向服务器发送走棋请求

            if (room_info.uid != room_info.white_id && room_info.uid != room_info.black_id)
            {
                alert("您无权操作");
                return;
            }

            if (global_winner != 0)
            {
                alert("游戏已结束，请返回大厅");
                return;
            }

            if (!is_me) {
                alert("等待对方走棋....");
                return;
            }
            
            let x = e.offsetX;
            let y = e.offsetY;
            // 注意, 横坐标是列, 纵坐标是行
            // 这里是为了让点击操作能够对应到网格线上
            let col = Math.floor(x / 30);
            let row = Math.floor(y / 30);
            if (chessBoard[row][col] != 0) {
                alert("当前位置已有棋子！");
                return;
            }

            clearTimeout(set_time_out_id);
            send_chess(row, col);
        }

        function send_chess(r, c)
        {
            var send_info = {
                optype : "put_chess",
                row : r,
                col : c,
                room_id : room_info.room_id,
                uid : room_info.uid
            }

            ws_hdl.send(JSON.stringify(send_info));
            console.log("click:" + JSON.stringify(send_info));
        }
        
        var ws_url = "ws://" + location.host + "/room";
        var ws_hdl = new WebSocket(ws_url);

        window.onbeforeunload = function(){
            ws_hdl.close();
        }
        
        ws_hdl.onopen = function(){
            console.log("进入游戏房间成功");
        }
        ws_hdl.onclose = function(){
            console.log("游戏房间断开");       
        }
        ws_hdl.onerror = function(){
            console.log("进入游戏房间出错");
        }

        function set_screen(me) {
            var screen_div = document.getElementById("screen");
            if (me) {
                screen_div.innerHTML = "到您走棋了...";
            }else {
                screen_div.innerHTML = "对方思考中...";
            }
        }

        ws_hdl.onmessage = function(evt){

            var info = JSON.parse(evt.data);
            console.log(JSON.stringify(info));

            if (info.optype == "room_ready")
            {
                initGame();
                room_info = info;

                if (info.winner != 0)
                {
                    var screen_div = document.getElementById("screen");           
                    screen_div.innerHTML = "游戏已经结束，请返回大厅";
                    return;
                }

                if (info.cur_op_id == info.uid)
                {
                    is_me = true;
                }
                else{
                    is_me = false;
                }
                //is_me = info.uid == info.white_id ? true : false;
                set_screen(is_me);

                if (info.uid == info.white_id)
                {
                    document.getElementById("user_tip").innerHTML = "当前您执黑子";
                }
                else if(info.uid == info.black_id)
                {
                    document.getElementById("user_tip").innerHTML = "当前您执白子";
                }
                            
                var cur_time = new Date();
                var tmp = cur_time.getTime() + 1000*90;        
                next_time = new Date(tmp);
                if_auto_select = false;
                count_down_fun();
             

                var room_flag_msg = "当前房间id号：";
                room_flag_msg += info["room_id"];
                var room_flag = document.getElementById("room_id_flag");
                room_flag.innerHTML = room_flag_msg;
                oneStep_viewer(info.board_msg);
                //alert(info.board_msg);
                if (room_info.uid != info.white_id && room_info.uid != info.black_id)
                {
                    var screen_div = document.getElementById("screen");           
                    screen_div.innerHTML = "等待棋手操作中...";
                }      
            }
            else if (info.optype == "put_chess")
            {
                console.log("put_chess" + evt.data);
                //走棋操作
                if (info.result == false) {
                    alert(info.reason);
                    return;
                }

                //设置是否有人胜利
                global_winner = info.winner;

                //当前走棋的用户id，与我自己的用户id相同，就是我自己走棋，走棋之后，就轮到对方了
                //当前用户如果是观战的，调用观战者信息
                if (room_info.uid != info.white_id && room_info.uid != info.black_id)
                {
                    
                    var screen_div = document.getElementById("screen");
                    if (info.uid == room_info.white_id) {
                        screen_div.innerHTML = "黑棋思考中...";
                        isWhite = true;

                    }else {
                        screen_div.innerHTML = "白棋思考中...";
                        isWhite = false;
                    }
                }
                else if(info.black_id < 0)
                {
                    if(info.winner == 0)
                    {
                        is_me = true;
                        set_screen(is_me);
                    }
                }
                else
                {
                    is_me = info.uid == room_info.uid ? false : true;
                    set_screen(is_me);
                    //绘制棋子的颜色，应该根据当前下棋角色的颜色确定
                    isWhite = info.uid == room_info.white_id ? true : false;
                }   

                //给棋手绘制棋子
                if (info.row != -1 && info.col != -1 )
                {
                    if (info.black_id < 0)
                    {
                        oneStep_viewer(info.board_msg);
                        if (info.winner == 0)
                        {
                            chessBoard[info.row][info.col] = 1;
                            chessBoard[info.ai_row][info.ai_col] = 1;
                        }
                    }
                    else{
                        oneStep(info.col, info.row, isWhite);
                        chessBoard[info.row][info.col] = 1;
                    }
                }

                //设置定时任务，超过思考时间自动走棋
                var cur_time = new Date();
                var tmp = cur_time.getTime() + 1000*90;        
                next_time = new Date(tmp);
                if_auto_select = false;
                count_down_fun();


                //是否有胜利者
                if (info.winner == 0 && info.if_game_over == false) {
                    return;
                }
                
                clearTimeout(set_time_out_id);
                var screen_div = document.getElementById("screen");
                
                if (room_info.uid == info.winner || (info.if_game_over == true && info.winner == 0)) {
                    screen_div.innerHTML = info.reason;
                }
                else if (room_info.uid != info.black_id && room_info.uid != info.white_id)
                {
                    if (info.winner == info.black_id)
                    {
                        screen_div.innerHTML = "白子获胜了";
                    }
                    else{
                        screen_div.innerHTML = "黑子获胜了";
                    }
                }
                else {
                    screen_div.innerHTML = "再接再厉呀";
                }

                clearTimeout(set_time_out_id);
            }
            else if (info.optype == "chat"){
                //将收到的消息显示到屏幕上，并且清空输入框中的内容
                //创建一个子标签
                var msg_div = document.createElement("p");
                msg_div.innerHTML = info.message;

                //区分消息是谁发的，给其进行CSS美化
                if (info.uid == room_info.uid) {
                    msg_div.setAttribute("id", "self_msg");
                }else {
                    msg_div.setAttribute("id", "peer_msg");
                }
                //添加一个换行标签
                var br_div = document.createElement("br");
                
                //将输入消息添加为子标签
                var msg_show_div = document.getElementById("chat_show");
                msg_show_div.appendChild(msg_div);
                msg_show_div.appendChild(br_div);
                msg_show_div.scrollTop = msg_show_div.scrollHeight;
            }
        }

         //给发送按钮添加点击事件，捕捉聊天输入框的消息，发送消息给服务器
        let chat_bt_div = document.getElementById('chat_button');
        chat_bt_div.onclick = function(){
            var chat_info = document.getElementById('chat_input').value;
            if (room_info.uid != room_info.white_id && room_info.uid != room_info.black_id)
            {
                document.getElementById("chat_input").value = "";
                alert("您无权这么做");
                return;          
            }

            if (chat_info.length > 0)
            {
                var send_msg = {
                    optype: "chat",
                    room_id: room_info.room_id,
                    uid: room_info.uid,
                    message: chat_info
                }
                ws_hdl.send(JSON.stringify(send_msg));
                document.getElementById("chat_input").value = "";
                //console.log(JSON.stringify(send_msg));
            }
        }

        var rt_bt = document.getElementById("return_hall");
        rt_bt.onclick = function(){
            console.log("返回对弈大厅");
            location.replace("/game_hall.html");
        }

        var sd_bt = document.getElementById("save_data");
        sd_bt.onclick = function(){
            if (confirm("是否保存游戏数据？"))
            {
                var send_msg = {
                    optype: "save_data",
                    room_id: room_info.room_id,
                    uid: room_info.uid
                }
                
                ws_hdl.send(JSON.stringify(send_msg));
                alert("保存成功，可在棋局复盘中查看");
            }
        }


        function count_down_fun(){
            var now = new Date();
            var diff = next_time.getTime() - now.getTime();
            var min = Math.floor(diff/(1000*60));
            var sec = Math.floor((diff/1000)%60);
            document.getElementById("count_down").innerHTML = "思考倒计时："+ min + " 分 "+ sec +" 秒";
            if (min <= 0 && sec <= 0 && if_auto_select == false)
            {
                if_auto_select = true;
                if (is_me == true)
                {
                    for (var i = 0; i < BOARD_ROW_AND_COL; i++)
                    {
                        for (var j = 0; j < BOARD_ROW_AND_COL; j++)
                        {
                            if (chessBoard[i][j] == 0)
                            {
                                send_chess(i, j);
                                return;
                            }
                        }
                    }
                }
            }
            
            if(global_winner == 0)
            {
                set_time_out_id = setTimeout("count_down_fun()", 1000);
            }
            else{
                hidden_sd_bt.hidden = false;
                document.getElementById("count_down").innerHTML = "游戏结束";
            }
        }
        
    </script>
</body>
</html>